import {isArray} from "@/utils/Validate";
import Modal from "@/utils/Modal";
import {openSetting} from "@/utils/Location";
import CacheUtils from "@/utils/CacheUtils";

/**
 * 加载图片
 * @param {string|number} src - 图片源（URL或ID）
 * @param {number|string} [height] - 图片高度
 * @param {number|string} [width] - 图片宽度
 * @returns {string} 处理后的图片URL
 */
export function loadImage(src, height, width) {
    // 处理空值情况
    if (!src) return "";

    // 统一转换为字符串处理
    src = src.toString();

    // 格式化高度和宽度参数
    const formatDimension = (dimension) => {
        if (!dimension) return null;
        return Number(dimension.toString().replace("rpx", ""));
    };

    const formattedHeight = formatDimension(height);
    const formattedWidth = formatDimension(width);

    // OSS处理开关
    const isOssEnabled = process.env.VUE_APP_OSS_URL === 'true';

    // 判断是否为图片ID（纯数字）
    const isImageId = /^\d+$/g.test(src);

    if (isOssEnabled) {
        // 处理完整的URL
        if (src.startsWith("http")) {
            // 判断是否为阿里云OSS
            const isOss = src.includes('aliyuncs.com') &&
                src.includes('oss-cn-') &&
                !src.includes('x-oss-process');

            // 判断是否为腾讯云COS
            const isCos = src.includes('.cos.') &&
                !src.includes('imageMogr2');

            // 确定URL参数连接符
            const prefix = src.includes('?') ? '&' : '?';

            // 阿里云OSS处理
            if (isOss) {
                if (formattedHeight) {
                    return `${src}${prefix}x-oss-process=image/resize,h_${formattedHeight},m_lfit`;
                }

                if (formattedWidth) {
                    return `${src}${prefix}x-oss-process=image/resize,w_${formattedWidth},m_lfit`;
                }
            }

            // 腾讯云COS处理
            if (isCos && formattedWidth && formattedHeight) {
                return `${src}${prefix}imageMogr2/thumbnail/${formattedWidth}x${formattedHeight}`;
            }

            // 其他情况直接返回原URL
            return src;
        }

        // 处理图片ID
        if (isImageId) {
            const baseUrl = `${process.env.VUE_APP_URL}${process.env.VUE_APP_IMG_URL}${src}`;

            if (formattedHeight) {
                return `${baseUrl}?x-oss-process=image/resize,h_${formattedHeight},m_lfit`;
            }

            if (formattedWidth) {
                return `${baseUrl}?x-oss-process=image/resize,w_${formattedWidth},m_lfit`;
            }

            return baseUrl;
        }
    } else {
        // 未开启OSS处理
        if (isImageId) {
            // 图片ID格式化为完整URL
            return `${process.env.VUE_APP_URL}${process.env.VUE_APP_IMG_URL}${src}`;
        }

        // 直接返回原URL
        return src;
    }
}

/**
 * @Description:选择文件
 * @param {Number} count 图片数量
 */
export function chooseImage(count = 1) {
    const promise = new Promise((resolve, reject) => {
        uni.chooseImage({
            count,
            success: (res) => {
                resolve(res.tempFilePaths)
            },
            fail: (err) => {
                reject(err)
            }
        })
    })
    return promise
}

/**
 * @Description:上传文件
 * @param {Array} tempFilePaths 图片路径
 * @param {String} btype
 */
export function upload(tempFilePaths, btype = '', url = process.env.VUE_APP_UPLOAD_URL) {
    if (!isArray(tempFilePaths)) {
        tempFilePaths = [tempFilePaths]
    }
    const promise = new Promise((resolve, reject) => {
        const data = []
        for (let filePath of tempFilePaths) {
            uni.uploadFile({
                url: `${process.env.VUE_APP_URL}${url}?btype=${btype}`,
                filePath,
                header: {
                    Token: CacheUtils.getCache('token'),
                    sessionId: CacheUtils.getCache('token'),
                },
                name: 'file',
                success: (res) => {
                    if (res.statusCode === 200) {
                        const response = JSON.parse(res.data);
                        if (typeof response.data === 'string') {
                           // LoginService.login();
                            // todo 登录过期
                            resolve([]);
                            return
                        }
                        data.push(response.data);
                        if (data.length === tempFilePaths.length) {
                            resolve(data)
                        }
                    }
                },
                fail: (err) => {
                    reject(err)
                }
            })
        }
    })
    return promise
}

/**
 * @Description:选择图片并上传
 * @param {Number} dataLength 最多选择图片的数量
 * @param {String} btype
 * @param {Number} max 最多上传图片的数量
 * @param {String} url 上传地址
 */
export async function chooseAndUpload(dataLength, btype = '', max = 1, url = process.env.VUE_APP_UPLOAD_URL) {
    if (dataLength === max) {
        Modal.toast(`最多上传${max}张图片`);
        return
    }
    const count = max - dataLength;
    const tempFilePaths = await chooseImage(count);
    return await upload(tempFilePaths, btype, url);
}

/**
 * @Description:预览图片
 * @param {Array} data 图片数组
 * @param {Number} index 索引
 * @param {String} name 键名
 */
export function preview(data, index, name) {
    if (!isArray(data)) {
        data = data.split(',')
    }
    uni.previewImage({
        urls: name ? data.map(item => item[name]) : data.map(item => loadImage(item)),
        current: index
    })
}

/**
 * @Description:下载附件
 * @param {String} id 文件id
 * @param {String} url 请求地址
 */
export function downloadFile(id, url = process.env.VUE_APP_DOWNLOAD_URL) {
    url = `${process.env.VUE_APP_URL}${url}${id}`
    const promise = new Promise((resolve, reject) => {
        uni.downloadFile({
            url,
            success: (res) => {
                resolve(res.tempFilePath)
            },
            fail: (err) => {
                console.log(err)
            }
        })
    })
    return promise
}

/**
 * @Description:保存到相册
 */
export function saveImageToPhotosAlbum(filePath) {
    const promise = new Promise((resolve, reject) => {
        uni.saveImageToPhotosAlbum({
            filePath,
            success: res => {
                Modal.toast('已保存到相册')
                resolve()
            },
            fail: async (err) => {
                reject()
                if (err.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
                    await Modal.confirm('请允许访问相册',);
                    await openSetting('scope.writePhotosAlbum')
                    await saveImageToPhotosAlbum(filePath)
                }
            }
        })
    })
    return promise
}
